type shell_color =
    White
  | Cyan
  | Magenta
  | Blue
  | Yellow
  | Green
  | Red
  | Black

type lightness =
    Bright
  | Dark

let teinte col = match Color.get col with
    (x,y,z) when (max x (max y z))=x -> (60*(y-z)/(x-(min y z))+360) mod 360
  | (x,y,z) when (max x (max y z))=y -> (60*(z-x)/(y-(min x z))+120)
  | (x,y,z) -> (60*(x-y)/(z-(min x y))+240)

let lumine col = match Color.get col with
    (x,y,z) -> float (max x (max y z)) /. 255.

let sature col = match Color.get col with
    (0,0,0) -> 0.
  | (x,y,z) -> 1. -. (float (min x (min y z))) /. (float (Color.average col))

let selcol = function
    c when (teinte c) < 30	-> Red
  | c when (teinte c) < 90	-> Yellow
  | c when (teinte c) < 150	-> Green
  | c when (teinte c) < 210	-> Cyan
  | c when (teinte c) < 270	-> Blue
  | c when (teinte c) < 330	-> Magenta
  | c				-> Red

let sellight = function
    c when (lumine c) > 0.5	-> Bright
  | _				-> Dark

let selwb = function
    c when (lumine c) > 0.85	-> (Bright, White)
  | c when (lumine c) > 0.60	-> (Dark, White)
  | c when (lumine c) > 0.15	-> (Bright, Black)
  | c				-> (Dark, Black)

let getcol = function
    White	-> 37
  | Cyan	-> 36
  | Magenta	-> 35
  | Blue	-> 34
  | Yellow	-> 33
  | Green	-> 32
  | Red		-> 31
  | Black	-> 30

let getlight = function
    Bright  -> 1
  | Dark    -> 0

let getwb = function
    (l,c) -> (getlight l,getcol c)

let prepare c =
  if (sature c) < 0.2 then getwb (selwb c)
  else (getlight (sellight c), getcol (selcol c))

let get_colored_str color str =
  match (prepare color) with
      (light,col) ->
 	Printf.printf "\027[%i;%im%s" light col str

let print (str, color) colored =
  if colored then
    let (ligth, col) = prepare color in
      Printf.printf "\027[%i;%im%s" ligth col str
  else
    Printf.printf "%s" str

let get_col color =
  let (l, c) = prepare color in
    c
